
import { ref, unref } from "vue";
import { baseURL } from "./http";
import wx from 'weixin-js-sdk'
import { useAuthStore } from "@/stores/counter";

const counter = ref<Recordable>({});
setTimeout(() => {
  counter.value = useAuthStore()
})
//所在环境
let client = null;
// #ifdef MP-WEIXIN
client = 1;
// #endif

// #ifdef H5
client = isWeixinClient() ? 2 : 6;
// #endif

// #ifdef APP-PLUS
client = 3;
uni.getSystemInfo({
  success: (res) => {
    client = res.platform == "ios" ? 3 : 4;
  },
  fail: (res) => {
    client = 3;
  },
});
// #endif
export { client };

//节流
export const trottle = (func: { apply: (arg0: any, arg1: any[]) => void; }, time = 1000, context: any) => {
  let previous = new Date(0).getTime();
  return function (...args: any[]) {
    let now = new Date().getTime();
    if (now - previous > time) {
      func.apply(context, args);
      previous = now;
    }
  };
};

//节流
export const debounce = (func: { apply: (arg0: any, arg1: any[]) => void; }, time = 1000, context: any) => {
  let timer: number | null | undefined = null;
  return function (...args: any[]) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      func.apply(context, args);
    }, time);
  };
};

//判断是否为微信环境
export function isWeixinClient() {
  // #ifdef H5
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    //这是微信环境
    return true;
  } else {
    //这是非微信环境
    return false;
  }
  // #endif
  // #ifndef H5
  return false;
  // #endif
}

//判断是否为安卓环境
export function isAndroid() {
  let u = navigator.userAgent;
  return u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
}

//获取url后的参数  以对象返回
export function strToParams(str: string) {
  const newparams: { [x: string]: any; } = {};
  for (let item of str.split("&")) {
    newparams[item.split("=")[0]] = item.split("=")[1];
  }
  return newparams;
}

//重写encodeURL函数
export function urlencode(str: string | number | boolean) {
  str = (str + "").toString();
  return encodeURIComponent(str)
    .replace(/!/g, "%21")
    .replace(/'/g, "%27")
    .replace(/\(/g, "%28")
    .replace(/\)/g, "%29")
    .replace(/\*/g, "%2A")
    .replace(/%20/g, "+");
}

//一维数组截取为二维数组

export function arraySlice(data: any[], array = [], optNum = 10) {
  data = JSON.parse(JSON.stringify(data));
  if (data.length <= optNum) {
    data.length > 0 && array.push(data);
    return array;
  }
  array.push(data.splice(0, optNum));
  return arraySlice(data, array, optNum);
}

//对象参数转为以？&拼接的字符
export function paramsToStr(params: { [x: string]: any; }) {
  let p = "";
  if (typeof params == "object") {
    p = "?";
    for (let props in params) {
      p += `${props}=${params[props]}&`;
    }
    p = p.slice(0, -1);
  }
  return p;
}

// 获取wxml元素

export function getRect(selector: string, all: any, context: any) {
  return new Promise(function (resolve) {
    let qurey = uni.createSelectorQuery();

    if (context) {
      qurey = uni.createSelectorQuery().in(context);
    }

    qurey[all ? "selectAll" : "select"](selector)
      .boundingClientRect(function (rect) {
        if (all && Array.isArray(rect) && rect.length) {
          resolve(rect);
        }
        if (!all && rect) {
          resolve(rect);
        }
      })
      .exec();
  });
}

// 轻提示
export function toast(info = {}, navigateOpt: { (): any; tab: number; url: string; } | undefined) {
  let title = info.title || "";
  let icon = info.icon || "none";
  let endtime = info.endtime || 2000;
  if (title)
    uni.showToast({
      title: title,
      icon: icon,
      duration: endtime,
    });
  if (navigateOpt != undefined) {
    if (typeof navigateOpt == "object") {
      let tab = navigateOpt.tab || 1,
        url = navigateOpt.url || "";
      switch (tab) {
        case 1:
          //跳转至 table
          setTimeout(function () {
            uni.switchTab({
              url: url,
            });
          }, endtime);
          break;
        case 2:
          //跳转至非table页面
          setTimeout(function () {
            uni.navigateTo({
              url: url,
            });
          }, endtime);
          break;
        case 3:
          //返回上页面
          setTimeout(function () {
            uni.navigateBack({
              delta: parseInt(url),
            });
          }, endtime);
          break;
        case 4:
          //关闭当前所有页面跳转至非table页面
          setTimeout(function () {
            uni.reLaunch({
              url: url,
            });
          }, endtime);
          break;
        case 5:
          //关闭当前页面跳转至非table页面
          setTimeout(function () {
            uni.redirectTo({
              url: url,
            });
          }, endtime);
          break;
      }
    } else if (typeof navigateOpt == "function") {
      setTimeout(function () {
        navigateOpt && navigateOpt();
      }, endtime);
    }
  }
}

//菜单跳转
export function menuJump(item: { is_tab: any; link: any; link_type: any; }) {
  const { is_tab, link, link_type } = item;
  switch (link_type) {
    case 1:
      // 本地跳转
      if (is_tab) {
        uni.switchTab({
          url: link,
        });
        return;
      }
      uni.navigateTo({
        url: link,
      });
      break;

    case 2:
      // webview
      uni.navigateTo({
        url: "/pages/webview/webview?url=" + link,
      });
      break;

    case 3: // tabbar
  }
}

export function uploadFile(path: any) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseURL + 'file/upload-image',
      filePath: path,
      name:"file" ,
      success: (res) => {
        try {
          console.log("uploadFile res ==> ", res);
          let data = JSON.parse(res.data);

          if (data.code == 200) {
            resolve(data.body);
          } else {
            reject();
          }
        } catch (e) {
          reject();
        }
      },
      fail: (err) => {
        reject();
      },
    });
  });
}

//当前页面

export function currentPage() {
  let pages = getCurrentPages();
  let currentPage = pages[pages.length - 1];
  return currentPage || {};
}

// H5复制方法
export function copy(str: string) {
  // #ifdef H5
  let aux = document.createElement("input");
  aux.setAttribute("value", str);
  document.body.appendChild(aux);
  aux.select();
  document.execCommand("copy");
  document.body.removeChild(aux);
  uni.showToast({
    title: "复制成功",
    icon: "none",
  });
  // #endif

  // #ifndef H5
  uni.setClipboardData({
    data: str.toString(),
  });
  // #endif
}

// #ifdef MP-WEIXIN
export function toLivePlayer(roomId: any) {
  wx.navigateTo({
    url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}`,
  });
}
// #endif
/**
 * @description 判断系统端
 */
export function getClient() {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success({ platform }) {
        resolve(platform);
      },
      fail(err) {
        reject(err);
        console.log(err);
      },
    });
  });
}
/**
 * @description 获取当前微信小程序基础库版本号
 */
export function getBaseLibraryVersion() {
  const { SDKVersion } = wx.getSystemInfoSync();
  return SDKVersion;
}
/**
 * @description 用于比较当前微信基础库版本与目标基础库版本
 * 示例用法：比较小程序基础库版本是否大于等于 2.12.0 compareWeChatVersion("2.12.0")
 * return 1 =>当前版本大于目标版本  return -1 =>当前版本小于目标版本 return 0 =>当前版本等于目标版本
 * @param {string} targetVersion 目标微信版本号
 *
 */
export function compareWeChatVersion(targetVersion: number) {
  const currentVersion = getBaseLibraryVersion();
  if (currentVersion === targetVersion) {
    return 0; // 当前版本与目标版本相同
  } else if (currentVersion > targetVersion) {
    return 1; // 当前版本大于目标版本
  } else {
    return -1; // 当前版本小于目标版本
  }
}

export function getTime(timeCount: { value: number }){
  const timeInfo = {
    testHour: 0,
    testMinute: 0,
    testSecond: 0,
  }
  timeInfo.testHour = Math.floor(timeCount.value / 3600)
  timeInfo.testMinute = Math.floor((timeCount.value - timeInfo.testHour * 3600) / 60)
  timeInfo.testSecond = timeCount.value - timeInfo.testHour * 3600 - timeInfo.testMinute * 60
  return timeInfo
}

// 图片路径
export function getImgUrl(url: string) {
  if (url && url.indexOf("http") > -1) {
    return url 
  }else{
    return counter.value.getconfige.oss_url + url
  }
}

// 根据经纬度计算距离
export function getDistance(lat1: number, lng1: number, lat2: number, lng2: number) {
  const radLat1 = (lat1 * Math.PI) / 180.0;
  const radLat2 = (lat2 * Math.PI) / 180.0;
  const a = radLat1 - radLat2;
  const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
  let s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    );
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  return s;
}

// 拨打电话
export function callPhone(phone: string) {
  uni.makePhoneCall({
    phoneNumber: phone,
  });
}

// 校验是否为手机号
export function checkPhone(phone: string) {
  const reg = /^1[3456789]\d{9}$/;
  return reg.test(phone);
}

export function timestampToDateJian(timestamp) {
  var date = new Date(timestamp);  // 将时间戳转换为Date对象
  var year = date.getFullYear();   // 获取年份
  var month = date.getMonth() + 1;  // 获取月份，需要+1因为月份是从0开始计算的
  var day = date.getDate();         // 获取日
  var hours = date.getHours();      // 获取小时
  var minutes = date.getMinutes();  // 获取分钟
  var seconds = date.getSeconds();  // 获取秒钟
 
  // 格式化月份和日期，如果小于10，则前面加0
  month = (month < 10 ? "0" : "") + month;
  day = (day < 10 ? "0" : "") + day;
  hours = (hours < 10 ? "0" : "") + hours;
  minutes = (minutes < 10 ? "0" : "") + minutes;
  seconds = (seconds < 10 ? "0" : "") + seconds;
 
  // 拼接字符串返回
  return year + "/" + month + "/" + day + " " + hours + ":" + minutes;
}

export function timestampToDateTime(timestamp) {
	  var date = new Date(timestamp);  // 将时间戳转换为Date对象
	  var year = date.getFullYear();   // 获取年份
	  var month = date.getMonth() + 1;  // 获取月份，需要+1因为月份是从0开始计算的
	  var day = date.getDate();         // 获取日
	  var hours = date.getHours();      // 获取小时
	  var minutes = date.getMinutes();  // 获取分钟
	  var seconds = date.getSeconds();  // 获取秒钟
	 
	  // 格式化月份和日期，如果小于10，则前面加0
	  month = (month < 10 ? "0" : "") + month;
	  day = (day < 10 ? "0" : "") + day;
	  hours = (hours < 10 ? "0" : "") + hours;
	  minutes = (minutes < 10 ? "0" : "") + minutes;
	  seconds = (seconds < 10 ? "0" : "") + seconds;
	 
	  // 拼接字符串返回
	  return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
	}
  export function timestampToDateTimes(timestamp) {
	  var date = new Date(timestamp);  // 将时间戳转换为Date对象
	  var year = date.getFullYear();   // 获取年份
	  var month = date.getMonth() + 1;  // 获取月份，需要+1因为月份是从0开始计算的
	  var day = date.getDate();         // 获取日
	  var hours = date.getHours();      // 获取小时
	  var minutes = date.getMinutes();  // 获取分钟
	  var seconds = date.getSeconds();  // 获取秒钟
	 
	  // 格式化月份和日期，如果小于10，则前面加0
	  month = (month < 10 ? "0" : "") + month;
	  day = (day < 10 ? "0" : "") + day;
	  hours = (hours < 10 ? "0" : "") + hours;
	  minutes = (minutes < 10 ? "0" : "") + minutes;
	  seconds = (seconds < 10 ? "0" : "") + seconds;
	 
	  // 拼接字符串返回
	  return year + "/" + month + "/" + day
	}
  // 倒计时
  export function getTimeDifference(timestamp: string): string {
    
    const currentTime = new Date().getTime();
    const difference = timeToTimestamp(timestamp) - currentTime;
    const time = {
      hour: 0,
      minute: 0,
      second: 0
    }
    if (difference < 0) {
      return JSON.stringify(time);
    }
    
    time.hour = Math.floor(difference / (1000 * 60 * 60));
    time.minute = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
    time.second = Math.floor((difference % (1000 * 60)) / 1000);
  
    return JSON.stringify(time);
  }

  export function timeToTimestamp(timeStr: string): number {
    return new Date(timeStr).getTime();
  }
  
  // 获取域名
  export function getURL(url: string,number:number){
    const href = url || window.location.href;
    const parts = href.split('#');
    const obj =  parts[number];
    return obj;
  }

  

  // 获取域名上的参数
  export function getURLParameters(url: string): Record<string, string> {
    const reg = /([^?=&]+)(=([^&#]*))/g;
    const href = url || window.location.href;
    const matchList = href.match(reg) || [];
    const obj = {};
  
    matchList.forEach((v) => {
      obj[v.slice(0, v.indexOf('='))] = decodeURIComponent(v.slice(v.indexOf('=') + 1));
    });
  
    return obj;
  }

  export function wxShare(data: any,type:number){
    const dataShare = ref<any>()
    const dataInfo = ref<any>()
    dataShare.value = counter.value.confige.wechat
    dataInfo.value = counter.value.dataUser
    const dataurl =ref<string>('')
    if(type===1){
      dataurl.value = getURL(location.href,0)+'#/?inviter_code='+unref(dataInfo).invite_code
    }else if(type===2){
      unref(dataShare).desc = data.name
      unref(dataShare).share_img = data.cover
      dataurl.value = dataurl.value = getURL(location.href,0)+'#/pages/shop/detail?inviter_code='+unref(dataInfo).invite_code+'&idcode='+data.code
    }else if(type===3){
      unref(dataShare).desc = data.name
      unref(dataShare).share_img = data.cover
      dataurl.value = dataurl.value = getURL(location.href,0)+'#/pages/live/zhibo?inviter_code='+unref(dataInfo).invite_code+'&zhibo_id='+data.id
    }
    wx.config({
      debug: false, // 是否开启调试模式
      appId: unref(dataShare).info.appId, // 必填，公众号的唯一标识
      timestamp: unref(dataShare).info.timestamp, // 必填，生成签名的时间戳
      nonceStr: unref(dataShare).info.nonceStr, // 必填，生成签名的随机串
      signature: unref(dataShare).info.signature, // 必填，签名，见附录1
      jsApiList: unref(dataShare).info.jsApiList
    })
    wx.error((res) =>{
      console.log(res)
    })
    wx.ready(() => {  
      wx.hideMenuItems({// 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
        menuList: ['menuItem:copyUrl', 'menuItem:openWithQQBrowser', 'menuItem:openWithSafari', 'menuItem:originPage']
      });
      wx.updateAppMessageShareData({ 
        title: unref(dataShare).title, // 分享标题
        desc: unref(dataShare).desc, // 分享描述
        link: dataurl.value, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: unref(dataShare).share_img, // 分享图标
        success: function () {
          // 设置成功
        }
      })
    });
    
    const obj =  {};
    return obj;
  }